(function() {
  var dataAlbumCropArr = {};
  var dataIntroImagesCropArr = {};
  var datalogoCropArr = {};
  var dataavatarCropArr = {};
  
	// getElementById
	function $id(id) {
		return document.getElementById(id);
	}
	
	// file selection
	function FileSelectHandler(e) {
		// fetch FileList object
		var files = e.target.files || e.dataTransfer.files;
		var id = e.currentTarget.getAttribute('id');
		
		// process all File objects
		ParseFile(files[0], id);
		UploadFile(files[0], id);
    
	    alert('Chọn vùng tương ứng để up ảnh.');
	   
	    var xsize = 98, ysize = 108, jcrop_api_logo;
	    
	    jQuery('.target_logo').each(function() {
	      image_to_crop_logo = $(this);
	      image_to_crop_logo.Jcrop({
	        //aspectRatio: xsize / ysize,
	        setSelect: [ 0, 0, xsize, ysize ],
	        //minSize: [ xsize/2, ysize/2 ],
	        //maxSize: [ xsize*2, ysize*2 ],
	        onSelect: function(coords){
	    	  datalogoCropArr[image_to_crop_logo.attr('id')] = coords;
	    	  // console.log(coords);
	   	      $('#dataRecruitmentCropJson').val($.toJSON(datalogoCropArr));
	      	}
	      },function(){
	    	  jcrop_api_logo = this;
	    	  jcrop_api_logo.animateTo([0,0,xsize,ysize]);
	      });
	    });
	}

	// output file information
	function ParseFile(file, id) {
		
		console.log(file.type);
		
		// display an image
		if (file.type.indexOf("image") == 0) {
			var reader = new FileReader();
			reader.onload = function(e) {
				var m_logo = $id("avatar_append");
				var msg = "<p><strong>" + file.name + ":</strong><br />" +
					'<img class="target_logo" id="' + file.name + '" src="' + e.target.result + '" /></p>';
				m_logo.innerHTML = msg + m_logo.innerHTML;
			};
			reader.readAsDataURL(file);
		}
	}


	// upload JPEG files
	function UploadFile(file, id) {
		var xhr = new XMLHttpRequest();
		if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
			// start upload
			xhr.open("POST", $id("upload_avatar").action, true);
			
			xhr.setRequestHeader("X_FILENAME", file.name);
			xhr.send(file);
		}
	}


	// initialize
	function Init() {
		var avatar = $id("avatar");
		
		// file select
		avatar.addEventListener("change", FileSelectHandler, false);

		// is XHR2 available?
		var xhr = new XMLHttpRequest();
		if (xhr.upload) {
			// remove submit button
			$(".submitbutton").css("display", "none");
		}

	}

	// call initialization file
	if (window.File && window.FileList && window.FileReader) {
		Init();
	}
})();